using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    CharacterController characterController;
    Camera mainCamera;
    float horizontal;
    float vertical;
    Vector3 direction;
    public float speed = 5f; // 玩家移动的速度
    
    void Start()
    {
        characterController = GetComponent<CharacterController>(); // 初始化角色控制器
        mainCamera = Camera.main;
    }

    void Update()
    {
        SetPlayerMove();

        SetPlayerRotation();
    }

    //处理角色移动
    void SetPlayerMove()
    {
        horizontal = Input.GetAxis("Horizontal");
        vertical = Input.GetAxis("Vertical");
        direction = new Vector3(horizontal, 0, vertical);
        characterController.SimpleMove(direction.normalized * speed);
    }

    // 处理角色旋转
    void SetPlayerRotation()
    {
        // 将鼠标屏幕坐标转换为世界坐标，设置z值为相机y位置
        Vector3 mousePos = mainCamera.ScreenToWorldPoint(new Vector3(
            Input.mousePosition.x,
            Input.mousePosition.y,
            mainCamera.transform.position.y));

        // 保持角色原有y轴高度
        mousePos.y = transform.position.y;

        // 让当前物体朝向鼠标世界坐标
        transform.LookAt(mousePos);
    }
}
